package com.cmcc.xdr.db;


import java.util.ArrayList;
import java.util.List;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.support.ClassPathXmlApplicationContext;
//import org.springframework.jdbc.core.JdbcTemplate; 

import com.cmcc.xdr.entity.HttpEntity;
import com.cmcc.xdr.util.JDBCUtil;
import com.cmcc.xdr.util.sql.HttpTransactionSaveSqlUtil;
public class PcapHttpDao{
	private static Logger logger = LogManager.getLogger(PcapHttpDao.class);
//	private static JdbcTemplate jdbcTemplate;
	//http_xdr入库sql语句

	public static final String httpXdrSql = "INSERT INTO xdr_http (LENGTH,LOCAL_PROVINCE,LOCAL_CITY,OWNER_PROVINCE,OWNER_CITY,ROAMING_TYPE,INTERFACE,XDR_ID,APP_TYPE_CODE,PROCEDURE_START_TIME,PROCEDURE_END_TIME,LONGITUDE,LATITUDE,HEIGHT,COORDINATE_SYSTEM,PROTOCOL_TYPE,APP_TYPE,APP_SUB_TYPE,APP_CONTENT,APP_STATUS,IP_ADDRESS_TYPE,USER_IPV4,USER_IPV6,USER_PORT,L4_PROTOCAL,APP_SERVER_IP_IPV4,APP_SERVER_IP_IPV6,APP_SERVER_PORT,UL_DATA,DL_DATA,UL_IP_PACKET,DL_IP_PACKET,UPDURA,DOWNDURA,UL_DISORDER_IP_PACKET,DL_DISORDER_IP_PACKET,UL_RETRANS_IP_PACKET,DL_RETRANS_IP_PACKET,TCP_RESPONSE_TIME,TCP_ACK_TIME,UL_IP_FRAG_PACKETS,DL_IP_FRAG_PACKETS,FIRST_REQ_TIME,FIRST_RESPONSE_TIME,WINDOW,MSS,TCP_SYN_NUM,TCP_STATUS,SESSION_END,TCP_SYN_ACK_NUM,TCP_ACK_NUM,TCP1_2_HANDSHAKE_STATUS,TCP2_3_HANDSHAKE_STATUS,UL_PROBEID,UL_LINK_INDEX,DL_PROBEID,DL_LINK_INDEX,TRANSACTIONID,FLOW_CONTROL,UL_AVG__RTT,DW_AVG__RTT,USER_ACCOUNT,REFER_XDR_ID,HTTP_VERSION,MESSAGE_TYPE,MESSAGE_STATUS,FIRST_HTTP_RESPONSE_TIME,LAST_CONTENT_PACKET_TIME,LAST_ACK_TIME,HOST_LENGTH,HOST,URI_LENGTH,URI,X_ONLINE_HOST_LENGTH,X_ONLINE_HOST,USER_AGENT_LENGTH,USER_AGENT,HTTP_CONTENT_TYPE,REFER_URI_LENGTH,REFER_URI,COOKIE_LENGTH,COOKIE,CONTENT_LENGTH,KEY_WORD,SERVICE_BEHAVIOR_FLAG,SERVICE_COMP_FLAG,SERVICE_TIME,IE,PORTAL,LOCATION_LENGTH,LOCATION,FIRST_REQUEST,USER_ACCOUNT_LOGIN,URI_TYPE,URI_SUB_TYPE,TASK_ID) VALUES ";
	
	//sql入库一次最多条数
	public static int sqlSize = 1000;
	
	//改dbcp连接池为jdbc连接
	/*static {
		try{
		    ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/applicationContext.xml"); //
		    jdbcTemplate = (JdbcTemplate)ctx.getBean("jdbcTemplate");
		}catch(Exception e){
			logger.error(e.getCause(),e);
		}
	}*/
	
	public static  void save(ArrayList<HttpEntity> httpEntityList,String taskId) {//此处参数应为一个list，里面存放的是一个tcpconnection中的拆分出来的所有httptransaction的数据，类型为List<HttpEntity>
		ArrayList<String> httpTransactionList = new ArrayList<String>();
		
		for(int i=0;i<httpEntityList.size();++i) {
			//如果包含单引号进行转义
    		if(httpEntityList.get(i).getHttpContentType() !=null && !("null").equals(httpEntityList.get(i).getHttpContentType())
    				&& httpEntityList.get(i).getHttpContentType().contains("'")){
    			httpEntityList.get(i).setHttpContentType(httpEntityList.get(i).getHttpContentType().replaceAll("'", "\""));
    		}
			httpTransactionList.add(HttpTransactionSaveSqlUtil.sql(httpEntityList.get(i),taskId));
		}
		
		if (httpTransactionList.size() > 0) {
			saveList(httpTransactionList, "xdr_http", httpXdrSql,"httpTransactionList");
		}
	}
	/**
	 * 解析后的http入库
	 * @param xdrList
	 * @param tableName
	 * @param xdrSql
	 * @param listName
	 */
	private static  void saveList(List<String> xdrList,String tableName ,String xdrSql,String listName) {
		Connection connection = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			connection = JDBCUtil.getConnection();
			st = connection.createStatement();
 			StringBuffer sql = new StringBuffer();
			if (xdrList.size() > 0) {
				if(xdrList.size() <= sqlSize){
					sql = new StringBuffer(xdrSql);
					//批量插入数据
					for (String string : xdrList) {
						sql.append(string);
						sql.append(",");
					}
					sql.deleteCharAt(sql.length() - 1);
					sql.append(";");
//					jdbcTemplate.execute(sql.toString());
					st.execute(sql.toString());
					logger.debug(xdrList.size() + ":SaveHttpTransaction.sql(HttpEntityList) "+sql.toString());
				}else{
					int bs = 0;//按照sqlSize 的一次入库次数，得到的总共需要执行循环的次数
					int lastSize = 0;//多次循环中最大的一行
					if(xdrList.size() % sqlSize == 0){//如果数量是最大入库行数的倍数则不加1
						bs = xdrList.size() / sqlSize;
					}else{
						bs = xdrList.size() / sqlSize +1;
					}
					logger.info("进入拆分sql,当前总共："+xdrList.size()+"条，需要分："+bs+"次执行");
					for(int y = 0;y < bs ;y++){//如果超过sqlSize条数据，则进行多次拼装sql入库
						sql = new StringBuffer(xdrSql);
						try{
							if(y+1 == bs){//如果是最后一次则直接提取最后的数量
								lastSize = xdrList.size();
							}else{
								lastSize = (y+1)*sqlSize;
							}
							for(int i = y*sqlSize;i < lastSize; i++){
								sql.append(xdrList.get(i));
								sql.append(",");
	//							sqlValue = xdrList.get(i) +"&;&";//用来标示入库错误后插入错误信息表
							}
							sql.deleteCharAt(sql.length() - 1);
							sql.append(";");
							logger.debug(xdrList.size() + ":sql="+sql.toString());
//							jdbcTemplate.execute(sql.toString());
							st.execute(sql.toString());
						}catch (Exception e) {//多条数据入库时出现问题则将多条数据拆开，一条一条入库
							logger.error("xdrList多数据入库异常，进入数据拆解模式（单条入库）---》");
							String sqlOne = "";
							try {
								for(int i = y*sqlSize;i < lastSize; i++){
									sqlOne = xdrSql+xdrList.get(i) + ";";
//								jdbcTemplate.execute(sqlOne);
								st.execute(sqlOne);
								}
							} catch (Exception e2) {
								logger.error("++++++++++++++");
								logger.error("xdrList单条数据入库异常=将插入异常信息到异常统计表sql:"+sqlOne+" ----",e2);
//								exceptionLogDeal(sqlOne,tableName,listName,"",e2);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("入库异常:",e);
//			exceptionDeal(st, xdrList,xdrSql, tableName, listName);
		}  finally {
			JDBCUtil.release(rs, st, connection);
		}
	}
	
	
	
	
}
